const app = getApp();
import Toast from 'tdesign-miniprogram/toast/index';
Page({
    // 轻提示
    toast(option) {
        Toast({
            context: this,
            selector: '#t-toast',
            ...option,
        });
    },
    data: {
        // 活动列表
        activity: [],
        pageInfo: {
            pageNum: 1,
            pageSize: 5,
        },
        hasMoreData: true, // 上拉/下拉时是否加载数据
    },
    onLoad() {
        this.findPage();
    },

    findPage() {
        // 开启加载效果
        this.toast({
            message: '加载中...',
            theme: 'loading',
            direction: 'column',
            duration: 1000
        });
        app.httpPost(`activity/page`, this.data.pageInfo).then((res) => {
            // 定义原有数据
            let temp = this.data.activity;
            // 接收新的结果
            let result = res.rows;
            if (result && result.length > 0) {
                // 用户下拉
                if (this.data.pageInfo.pageNum == 1) {
                    temp = [];
                }
                const rows = result.filter(item => {
                    if (item.image) {
                        item.image = item.image.split(',').map(i => (app.getImageUrl(i)))
                    }
                    if (item.createdAt) {
                        item.createdAt = app.formatTime(item.createdAt, 'YYYY-MM-DD HH:mm:ss');
                    }
                    return true;
                });
                // 如果结果长度大于分页数，则说明还可以上拉
                if (result.length < this.data.pageInfo.pageSize) {
                    this.setData({ hasMoreData: false, activity: temp.concat(rows) });
                } else {
                    this.setData({ hasMoreData: true, activity: temp.concat(rows), pageInfo: { pageNum: this.data.pageInfo.pageNum + 1, pageSize
                    : 5 } });
                }
            } else {
                this.setData({ hasMoreData: false });
            }
        });
    },

    onShow: function () {
        this.getTabBar().init();
    },

    /**
     * 用户下拉操作
     */
    onPullDownRefresh() {
        this.setData({ hasMoreData: true });
        this.setData({
            pageInfo: {
                pageNum: 1,
                pageSize: 5,
            }
        });
        this.findPage();
    },

    onReachBottom: function() {
        if (this.data.hasMoreData) {
            this.findPage();
        } else {
            this.toast({
                message: '没有跟多数据了！',
                theme: 'success',
                duration: 1000
            });
        }
    }
})